/*
 * ============================================================================
 *                   GNU Lesser General Public License
 * ============================================================================
 *
 *
 *
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 * 
 *
 *
 */
package rad.framework.jaxr;

import javax.xml.rpc.Stub;
import javax.xml.rpc.handler.MessageContext;

import rad.framework.jaxr.DiscoveryServiceMBean;
import rad.framework.jaxrpc.BaseHandler;
import rad.framework.jmx.JMXUtil;

/**
 * 
 * @author boudyacho
 * @deprecated
 * 
 */
public class DiscoveryHandler extends BaseHandler {

	// TODO get from wsdl?
	public static final String SERVICE_NAME = "serviceName";

	public boolean handleRequest(MessageContext ctx) {
		String uri = discover(getInitParam(SERVICE_NAME),
				getEndpointAddress(ctx));
		setEndpointAddress(ctx, uri);
		return true;
	}

	protected String getEndpointAddress(MessageContext ctx) {
		return (String) ctx.getProperty(Stub.ENDPOINT_ADDRESS_PROPERTY);
	}

	protected void setEndpointAddress(MessageContext ctx, String uri) {
		ctx.setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, uri);
	}

	protected String discover(String serviceName, String defaultValue) {
		String url = null;
		try {
			// TODO local transport having managed transaction issues
			url = getDiscoveryService().discover(serviceName);
		} catch (Exception e) {
			// just log and fail over to the default endpoint address
			logger.warn(this, e);
		}
		if (url == null) {
			url = defaultValue;
		}
		return url;
	}

	/**
	 * This handler is only intended to be used with clients executing inside
	 * the app server. Hence the mbean dependency.
	 * 
	 * @return
	 */
	protected DiscoveryServiceMBean getDiscoveryService() {
		return (DiscoveryServiceMBean) JMXUtil.getMBean(
				DiscoveryServiceMBean.class, DiscoveryServiceMBean.OBJECT_NAME);
	}
}
